package com.nlelpct.manage.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nlelpct.manage.constant.SystemConstant;
import com.nlelpct.manage.context.ThreadParameter;
import com.nlelpct.manage.mapper.UserMapper;
import com.nlelpct.manage.model.entity.User;
import com.nlelpct.manage.model.security.MyUser;
import com.nlelpct.manage.utils.LoginPasswordEncoderUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import cn.hutool.core.util.ObjectUtil;

import java.util.Arrays;

/**
 * @author :小马
 * @date : 2023-07-12
 */
@Component
@Slf4j
public class SecurityUserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Autowired
    public SecurityUserDetailsServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 通过用户名获取用户信息和权限信息
     * 权限信息：
     * 角色以 `ROLE_` 开头
     * 权限不能以 `ROLE_` 开头
     *
     * @param username 用户名
     * @return 用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser myUser = new MyUser();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, username);
        queryWrapper.select(User::getId, User::getPhone, User::getPassword, User::getZt, User::getLastResetPasswd);
        User user = userMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("");
        }
        if (!SystemConstant.USER_STATUS_NORMAL.equals(user.getZt())) {
            ThreadParameter.getLocalMap().put(SystemConstant.OTHER_ERROR, SystemConstant.OTHER_ERROR);
        }
        ThreadParameter.getLocalMap().put(SystemConstant.USER_INFO, JSON.toJSONString(user));
        myUser.setEnabled(user.getZt().equals(SystemConstant.USER_STATUS_NORMAL));
        myUser.setUserId(user.getId());
        myUser.setUsername(username);
        myUser.setPassword(LoginPasswordEncoderUtils.encode(user.getPassword()));
        //todo 获取该用户的权限集合 -- 目前默认给一个admin角色
        myUser.setRoles(Arrays.asList("ROLE_admin", "READ_getInfo"));
        return myUser;
    }
}
